const express = require('express');
const app = express();
const port = 8080;
// 引入ws库
const WebSocket = require('ws');

// 创建WebSocket服务器
const wss = new WebSocket.Server({ noServer: true });

wss.on('connection', (ws) => {
    console.log('新的WebSocket连接');

    ws.on('message', (message) => {
        console.log(`收到消息: ${message}`);
        // 可以在这里对消息进行处理，然后发送响应
        ws.send(`你发送的消息是: ${message}`);
    });

    ws.on('close', () => {
        console.log('WebSocket连接关闭');
    });
});

app.get('/', (req, res) => {
    res.send('Hello, World!');
});

const server = app.listen(port, () => {
    console.log(`Server running on port ${port}`);
});

// 将WebSocket服务器与Express服务器关联
server.on('upgrade', (request, socket, head) => {
    wss.handleUpgrade(request, socket, head, (ws) => {
        wss.emit('connection', ws, request);
    });
});